<!--
 * @Descripttion:  
 * @version:  
 * @Author: chenxf
 * @Date: 2023-03-08 09:41:30
-->
<template>
  <div class="user-select-cotainer">
    <a-input-group compact>
      <a-input
        :value="texts.join()"
        placeholder="请选择"
        style="width:calc(100% - 80px)"
        readOnly
        @change="() => {}"
        @click="showTable"
      ></a-input>
      <a-button @click="showTable" style="width:80px" type="primary">选择</a-button></a-input-group
    >
    <a-modal
      :title="'部门选择'"
      :key="'userSelect'"
      :bodyStyle="bodyStyle"
      :width="modalWidth"
      :visible="visible"
      v-if="visible"
      destroyOnClose
      :footer="null"
      @cancel="hideTable"
    >
      <div>
        <div class="header"></div>
        <div class="table-container" :style="{ height: tableHeight }">
          <!--组织机构-->
          <a-tree
            :selectable="true"
            multiple
            :checkable="true"
            :defaultCheckedKeys="selectedRowKeys"
            :checkKeys="{ checked: selectedRowKeys, halfChecked: [] }"
            :checkStrictly="true"
            @check="this.onSelectChange"
            :expandedKeys="expandedKeys"
            :dropdownStyle="{ maxHeight: tableHeight, overflow: 'auto' }"
            :treeData="dataSource"
            @expand="onExpand"
          />
        </div>
        <div class="footer">
          <a-button type="danger" @click="cleanAll" v-if="selectedRowKeys.length" ghost>清空</a-button>
          <a-button type="primary" @click="submitEvent">选择({{ selectedRowKeys.length }})</a-button>
          <a-button @click="hideTable">关闭</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { httpAction, getAction, postAction, putAction, deleteAction } from '@/api/manage'
export default {
  name: 'deptSelect',
  components: {},
  props: {
    showInput: {
      type: Boolean,
      default: true
    },
    value: {
      type: String
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      visible: false,
      modalWidth: 1300,
      bodyStyle: {
        padding: '20px',
        top: 0,
        height: window.innerHeight - 80 + 'px'
      },
      tableHeight: window.innerHeight - 280 + 'px',
      dataSource: [],
      queryParam: {
        realname: '',
        tenantName: '',
        phone: '',
        username: '',
        tenantId: ''
      },
      columns: [],
      pagination: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true
      },
      userUrl: '/auth/departs/trees',
      columns: [],
      selectedRowKeys: [],
      texts: [],
      userDict: {},
      isLoading: false,
      tenantsOpitons: [],
      expandedKeys: [],
      checkStrictly: true
    }
  },
  computed: {
    rowSelection() {
      const { selectedRowKeys } = this
      return {
        selectedRowKeys,
        onChange: this.onSelectChange,
        hideDefaultSelections: true,
        onSelection: this.onSelection
      }
    }
  },
  watch: {
    value: {
      handler() {
        this.transfromText()
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.getUserData()
    this.transfromText()
  },
  methods: {
    showTable() {
      this.visible = true
    },
    hideTable() {
      this.visible = false
    },
    search() {
      this.pagination.pageNo = 1
      this.getUserData()
    },
    getUserData() {
      const postData = {
        pageNo: this.pagination.pageNo,
        pageSize: this.pagination.pageSize,
        ...this.queryParam
      }
      this.isLoading = true
      getAction(this.userUrl, postData).then(res => {
        this.dataSource = res.result
        for (let i = 0; i < res.result.length; i++) {
          this.getAllKeys(res.result[i])
        }
        this.isLoading = false
      })
    },
    onSelectChange(keys) {
      this.selectedRowKeys = keys.checked
    },
    onSelection(keys) {
      this.selectedRowKeys = keys
    },
    handleTableChange(pagination, filters, sorter) {
      console.log(pagination)
      const pager = { ...this.pagination }
      pager.pageNo = pagination.current
      pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.getUserData()
    },
    change() {
      this.$emit('change', this.selectedRowKeys.join())
    },
    submitEvent() {
      this.$emit('change', this.selectedRowKeys.join())
      this.hideTable()
    },
    transfromText() {
      if (this.value) {
        this.selectedRowKeys = this.value && this.value.split(',')
        let promiseList = []
        this.selectedRowKeys.forEach(item => {
          promiseList.push(this.getUserById(item))
        })
        if (promiseList.length) {
          Promise.all([...promiseList])
            .then(res => {
              this.texts = res.map(res => {
                return res
              })
            })
            .catch(() => {
              this.texts = this.selectedRowKeys
            })
        }
      } else {
        this.selectedRowKeys = []
        this.texts = []
      }
    },
    getUserById(value) {
      return new Promise(resolve => {
        if (this.userDict[value]) {
          resolve(this.userDict[value].departName)
        } else {
          getAction('/auth/departs/' + value).then(res => {
            if (res.success) {
              this.userDict[res.result.id] = { ...res.result, id: res.result.id }
              resolve(res.result.departName)
            } else {
              resolve(value)
            }
          })
        }
      })
    },
    cleanAll() {
      this.selectedRowKeys = []
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
    },
    getAllKeys(node) {
      this.expandedKeys.push(node.key)
      if (node.children && node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          this.getAllKeys(node.children[a])
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-modal {
  top: 0;
  padding: 0;
}
.header {
  padding-bottom: 10px;
  .header-search {
    padding-top: 10px;
  }
}
.table-container {
  overflow: auto;
}
.footer {
  text-align: center;
  margin: auto;
  padding-top: 10px;
  button {
    margin-right: 10px;
  }
}
</style>
